var instance = axios.create({
  baseURL: 'http://web.lj8866.xin/api',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
instance.interceptors.request.use(
  function (config) {
    // const token = localStorage.getItem('token')
    // if (token) {
    //   Object.assign(config.headers, {'X-AUTH-TOKEN': token});
    // }
    // config.url = '/api' + config.url
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  function (res) {
    return res
  },
  function (error) {
    return Promise.reject(error.response)
  }
)


/*
* get请求
* @param url
* @param data
* @param set
* @returns {Promise}
*/
function apiGet(url, data, set) {
  data = data || {}
  set = set || {}
  if (set.timeout === undefined) set.timeout = 5000 // 设置响应时间

  return new Promise(function (resolve, reject) {
    instance.get(url, {
      params: data,
      timeout: set.timeout,
    }).then(function (response) {
      resolve(response)
    }).catch(function (error) {
      reject(error)
    })
  })
}

/*
* post请求, 可以设置参数用来上传文件
* @param url
* @param data
* @param set
* @returns {Promise}
*/
function apiPost(url, data, set) {
  data = data || {}
  set = set || {}
  return new Promise(function (resolve, reject) {
    instance.post(url, data, set).then(function (response) {
      resolve(response)
    }).catch(function (error) {
      reject(error)
    })
  })
}

Vue.apiGet = apiGet
Vue.apiPost = apiPost
Vue.prototype.apiGet = apiGet
Vue.prototype.apiPost = apiPost
